/**
 * Created by qunxing.du on 2016/8/16.
 * Copyright 2016 汉威.智慧环保事业部 Limited.
 * All rights reserved.
 */
package com.hw.one.collect.pollution.server;

import com.alibaba.fastjson.JSON;
import com.hw.one.collect.message.Message;
import com.hw.one.collect.message.ResultMessage;
import com.hw.one.collect.model.DataSrcType;
import com.hw.one.collect.model.DataType;
import com.hw.one.collect.pollution.server.data.PollutionDataService;
import com.hw.one.collect.resource.BaseContext;
import com.hw.one.collect.util.ConvertUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.apache.log4j.Logger;

import java.util.Map;

/**
 * 原始数据处理器
 */
public class PollutionRawDataHandler extends ChannelInboundHandlerAdapter {
    private static Logger log = Logger.getLogger(PollutionRawDataHandler.class);


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Map<String,Object> receivedData = ConvertUtil.toMap(msg);
        log.debug("数据源分类：" + receivedData.get("type"));
        log.debug("数据分类：" + receivedData.get("table"));
        String type = (String) receivedData.get("type");
        String table = (String) receivedData.get("table");
        if(DataSrcType.POLLUTION.name().equals(type)){
            Object data = receivedData.get("data");
            PollutionDataService pollutionDataService = (PollutionDataService) BaseContext.getService("pollutionDataService");
            if(DataType.ENT_BASIC_INFO.name().equals(table)){
                pollutionDataService.insertEntBasicInfo(table,data);
                success(ctx);
            } else  if(DataType.VENT.name().equals(table)){
                pollutionDataService.insertVent(table,data);
                success(ctx);
            }else   if(DataType.POLLUTANT_SET_INFO.name().equals(table)){
                pollutionDataService.insertPollutantSetInfo(table,data);
                success(ctx);
            }else {
                pollutionDataService.insertExhaust(table,data);
                ctx.fireChannelRead(receivedData);
            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        log.error("异常：",cause);
        Message resultMsg = new ResultMessage("999","error");
        ctx.writeAndFlush(JSON.toJSONString(resultMsg));
    }

    private void success(ChannelHandlerContext ctx){
        Message resultMsg = new ResultMessage("111","success");
        ctx.writeAndFlush(JSON.toJSONString(resultMsg));
    }
}
